package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Author : Jungle
 * @Description :
 */
@Controller
public class LoginController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){
        return stringRedisTemplate.opsForValue().get(token);
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token",required = false) String sso_token){
        if (!StringUtils.isEmpty(sso_token)){
        //    说明之前有人登录过，浏览器留下痕迹
            return "redirect:" + url+"?token="+sso_token;
        }
        model.addAttribute("url", url);
        return "login";
    }
    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password")String password,
                          @RequestParam("url")String url,
                          HttpServletResponse response){

        if (!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(password)){
            //登录成功跳转,跳回到之前的页面
            //把登录成功的用户存起来
            String uuid = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(uuid,username);
            Cookie cookie = new Cookie("sso_token",uuid);
            //1、浏览器要给ssoServer域名下保存 cookie  ==》作用 浏览器以后访问这个域名都要带上这个域名下的所有cookie
            //2、重定向到之前页面
            response.addCookie(cookie);
            return "redirect:" + url+"?token="+uuid;

        }
        //登录失败，继续在登录页面
        return "login";
    }
}
